import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;

@WebServlet("/list_book")
public class ListBook extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://101.37.236.199/linux_exam?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String USER = "root";
    private static final String PASSWORD = "1qaz@WSX#EDC";
    private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Class.forName(DRIVER_CLASS);
            Connection conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
            String sql = "SELECT number, name, author FROM t_book";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            StringBuilder json = new StringBuilder();
            json.append("{\"success\": true, \"message\": \"查询成功\", \"data\": [");
            boolean first = true;
            while (rs.next()) {
                if (!first) {
                    json.append(", ");
                }
                json.append("{\"number\": \"").append(rs.getString("number")).append("\", ");
                json.append("\"name\": \"").append(rs.getString("name")).append("\", ");
                json.append("\"author\": \"").append(rs.getString("author")).append("\"}");
                first = false;
            }

            json.append("]}");

            out.print(json.toString());
            rs.close();
            stmt.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            out.print("{\"success\": false, \"message\": \"数据库驱动加载失败\", \"error\": \"" + e.getMessage() + "\"}");
        } catch (SQLException e) {
            out.print("{\"success\": false, \"message\": \"数据库操作失败\", \"error\": \"" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
}
